// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
  })

// 云函数入口函数
exports.main = async (event, context) => {
    const db = cloud.database()
    // db.collection("counters")

    //获取年月
    let ymd = getNowFormatDate()
    if(event.ymd){
        ymd = event.ymd
    }


    //查询当天体重
    const currentDateHealth = await db.collection('health_rdl')
        .where({
            openId: event.userInfo.openId,
            time:ymd
        })
        .limit(1)
        .get()
        .then(res => {
            console.error("查询当天体重返回", res)
            if (res.data) {
                return res.data[0]
            }
            return res.data
        })
        .catch(res => {
            console.error("查询当天体重错误", res)
        })


    return {
        currentDateHealth: currentDateHealth
    }
}


function getNowFormatDate() {
    let date = new Date();
    let sep = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = year + sep + month + sep + strDate;
    return currentDate;
}
